package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Transactional
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private ApLikesBehaviorService apLikesBehaviorService;

    /**
     * 点赞或取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //如果传来的点赞的字段不等于0也不等于1的话 返回
        if (dto==null||dto.getArticleId()==null||(!dto.getType().equals((short)0)&&!dto.getType().equals((short)1))||
                (!dto.getOperation().equals((short)0)&&!dto.getOperation().equals((short)1))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户id 或者设备id 查询到行为实体
        Integer userID = AppThreadLocalUtils.getUser().getId();
        ApBehaviorEntry enhaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userID, dto.getEquipmentId());
        if (enhaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"找不到行为实体");
        }
        //根据行为实体 查询点赞表
        ApLikesBehavior like = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, enhaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
        if (like==null){
            //如果没有 添加
            ApLikesBehavior likesBehavior = new ApLikesBehavior();
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setCreatedTime(new Date());
            likesBehavior.setEntryId(enhaviorEntry.getId());
            likesBehavior.setType((short)0);
            likesBehavior.setOperation(dto.getOperation());
            save(likesBehavior);
        }else {
            //如果有 修改operation字段 为前端传来的字段
            like.setOperation(dto.getOperation());
            updateById(like);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}